from fastapi import APIRouter, Depends, Form, Request, Query, HTTPException, File, UploadFile
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
from sqlalchemy.orm import Session
from typing import Optional
from pydantic import BaseModel
from ..models import get_db, Link, LinkCategory, User, WebsiteConfig
from ..auth import get_current_user
from ..utils import paginate_query, save_uploaded_icon
import os
from fastapi.templating import Jinja2Templates

# 状态切换请求模型
class ToggleStatusRequest(BaseModel):
    new_status: bool

router = APIRouter()

# 获取模板目录
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
templates = Jinja2Templates(directory=os.path.join(BASE_DIR, "templates"))

# 网站链接列表页面
@router.get("/links", response_class=HTMLResponse)
async def admin_links(
    request: Request, 
    page: int = Query(1, ge=1), 
    db: Session = Depends(get_db), 
    current_user: User = Depends(get_current_user)
):
    # 添加外连接以获取分类信息
    query = db.query(Link, LinkCategory.name.label('category_name')).outerjoin(LinkCategory).order_by(Link.id)
    results = query.all()
    
    # 处理结果，将分类名称添加到链接对象中
    links_with_category = []
    for link, category_name in results:
        link.category_name = category_name or ''  # 如果没有分类，设为空字符串
        links_with_category.append(link)
    
    # 手动进行分页
    total_items = len(links_with_category)
    page_size = 20
    total_pages = (total_items + page_size - 1) // page_size
    current_page = min(page, total_pages)
    start_index = (current_page - 1) * page_size
    end_index = start_index + page_size
    
    pagination = {
        "items": links_with_category[start_index:end_index],
        "current_page": current_page,
        "total_pages": total_pages,
        "total_items": total_items,
        "page_size": page_size
    }
    
    # 获取网站配置
    config = db.query(WebsiteConfig).first()
    if not config:
        config = WebsiteConfig(background_effect="gradient")
    
    return templates.TemplateResponse("admin/links.html", {
        "request": request, 
        "links": pagination["items"],
        "current_page": pagination["current_page"],
        "total_pages": pagination["total_pages"],
        "total_items": pagination["total_items"],
        "page_size": pagination["page_size"],
        "current_user": current_user,
        "config": config
    })

# 添加网站链接页面
@router.get("/links/add", response_class=HTMLResponse)
async def admin_add_link(
    request: Request, 
    db: Session = Depends(get_db), 
    current_user: User = Depends(get_current_user)
):
    categories = db.query(LinkCategory).filter(LinkCategory.status == True).all()
    # 获取网站配置
    config = db.query(WebsiteConfig).first()
    if not config:
        config = WebsiteConfig(background_effect="stars")
    return templates.TemplateResponse(
        "admin/link-form.html", 
        {"request": request, "action": "add", "categories": categories, "current_user": current_user, "config": config}
    )

# 编辑网站链接页面
@router.get("/links/edit/{link_id}", response_class=HTMLResponse)
async def admin_edit_link(
    request: Request, 
    link_id: int, 
    db: Session = Depends(get_db), 
    current_user: User = Depends(get_current_user)
):
    link = db.query(Link).filter(Link.id == link_id).first()
    if not link:
        raise HTTPException(status_code=404, detail="网站链接不存在")
    categories = db.query(LinkCategory).filter(LinkCategory.status == True).all()
    # 获取网站配置
    config = db.query(WebsiteConfig).first()
    if not config:
        config = WebsiteConfig(background_effect="stars")
    return templates.TemplateResponse(
        "admin/link-form.html", 
        {"request": request, "link": link, "action": "edit", "categories": categories, "current_user": current_user, "config": config}
    )

# 保存网站链接
@router.post("/links/save")
async def save_link(
    request: Request,
    id: Optional[int] = Form(None),
    name: str = Form(...),
    category_id: Optional[int] = Form(None),
    url: str = Form(...),
    icon_file: Optional[UploadFile] = File(None),
    existing_icon: Optional[str] = Form(None),
    remove_icon: bool = Form(False),
    description: Optional[str] = Form(None),
    is_active: bool = Form(False),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    # 初始化图标变量
    icon = existing_icon
    
    # 如果选择了移除图标，则设置为None
    if remove_icon:
        icon = None
    # 如果有新上传的图标文件，则保存并更新图标路径
    elif icon_file and icon_file.filename:
        try:
            # 保存上传的图标文件
            icon = save_uploaded_icon(icon_file)
        except Exception as e:
            print(f"保存图标文件失败: {e}")
    
    # 处理category_id，空字符串或None都转换为None
    category_id = int(category_id) if category_id and str(category_id).strip() else None
    
    if id:
        link = db.query(Link).filter(Link.id == id).first()
        if not link:
            raise HTTPException(status_code=404, detail="网站链接不存在")
        link.name = name
        link.category_id = category_id
        link.url = url
        link.icon = icon
        link.description = description
        link.status = is_active
    else:
        link = Link(
            name=name,
            category_id=category_id,
            url=url,
            icon=icon,
            description=description,
            status=is_active
        )
        db.add(link)
    db.commit()
    return RedirectResponse(url="/admin/links", status_code=302)

# 删除网站链接
@router.post("/links/delete/{link_id}")
async def delete_link(
    link_id: int,
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    link = db.query(Link).filter(Link.id == link_id).first()
    
    # 检查是否是异步请求
    is_ajax = request.headers.get("X-Requested-With") == "XMLHttpRequest"
    
    if not link:
        if is_ajax:
            return {"success": False, "message": "网站链接不存在"}
        else:
            raise HTTPException(status_code=404, detail="网站链接不存在")
    
    db.delete(link)
    db.commit()
    
    if is_ajax:
        return {"success": True, "message": "删除成功"}
    else:
        return RedirectResponse(url="/admin/links?message=删除成功", status_code=302)

# 批量删除网站链接
@router.post("/links/batch-delete")
async def batch_delete_links(
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    form_data = await request.form()
    link_ids = form_data.getlist("link_ids")
    
    # 检查是否是异步请求
    is_ajax = request.headers.get("X-Requested-With") == "XMLHttpRequest"
    
    if not link_ids:
        if is_ajax:
            return {"success": False, "message": "请选择要删除的链接"}
        else:
            return RedirectResponse(url="/admin/links?message=请选择要删除的链接", status_code=302)
    
    # 将字符串ID列表转换为整数列表
    link_ids = [int(id) for id in link_ids]
    # 批量删除选中的网站链接
    db.query(Link).filter(Link.id.in_(link_ids)).delete(synchronize_session=False)
    db.commit()
    
    if is_ajax:
        return {"success": True, "message": "批量删除成功"}
    else:
        return RedirectResponse(url="/admin/links?message=批量删除成功", status_code=302)

# 切换网站链接状态
@router.post("/links/toggle-status/{link_id}")
async def toggle_link_status(
    link_id: int,
    request_data: ToggleStatusRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    try:
        # 查找网站链接
        link = db.query(Link).filter(Link.id == link_id).first()
        
        if not link:
            return JSONResponse(
                content={"success": False, "message": "网站链接不存在"},
                status_code=404
            )
        
        # 更新状态（这里应该是取反当前状态，而不是直接使用new_status）
        link.status = not link.status
        db.commit()
        
        status_text = "启用" if link.status else "禁用"
        return JSONResponse(
            content={"success": True, "message": f"网站链接{status_text}成功", "new_status": link.status}
        )
    except Exception as e:
        db.rollback()
        return JSONResponse(
            content={"success": False, "message": f"状态切换失败: {str(e)}"},
            status_code=500
        )